﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AMail.Common.Interfaces.Data;
using AMail.Common;

namespace AMail.Modules.Data.Actions
{
  public class DeleteFoldersAction : IMailAction
  {
    private List<IMailFolder> deletedFolders;
    private IMailFolder previousParentFolder;

    public DeleteFoldersAction(IEnumerable<IMailFolder> deletedFolders, IMailFolder previousParentFolder)
    {
      this.previousParentFolder = previousParentFolder;
      this.deletedFolders = new List<IMailFolder>(deletedFolders);
    }

    public DeleteFoldersAction(IMailFolder deletedFolder, IMailFolder previousParentFolder)
    {
      this.previousParentFolder = previousParentFolder;
      this.deletedFolders = new List<IMailFolder> { deletedFolder };
    }

    #region IMailAction Members

    public void Commit(IMailArchiver archiver)
    {
      var messagesToDelete = new List<IMailMessage>();
      foreach (var folder in this.deletedFolders)
        folder.FindAllMessages(messagesToDelete);
      
      foreach (var message in messagesToDelete)
        archiver.DeleteMessage(message);
    }

    public void Undo()
    {
      foreach (var folder in this.deletedFolders)
        folder.ParentFolder = this.previousParentFolder;
    }

    #endregion

    public override string ToString()
    {
      if (this.deletedFolders.Count == 1)
        return string.Format("Deleted folder '{0}' from '{1}'", this.deletedFolders[0].Name, this.previousParentFolder.Name);
      else
        return string.Format("Deleted {0} folders from '{1}'", this.deletedFolders.Count, this.previousParentFolder.Name);
    }

  }
}
